from flask_admin import Admin
from flask_admin.contrib.mongoengine import ModelView
from flask_admin.base import   MenuLink,AdminIndexView
from flask_login import  current_user
from app import flask_bcrypt
from flask import flash
from models import User,Mov
from app import app


class MyModelView(ModelView):
    def is_accessible(self):
        return current_user.isAdmin

class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        return current_user.isAdmin



class UserView(MyModelView):
    column_filters = ['email']
    def create_model(self, form):
        form.password.data = flask_bcrypt.generate_password_hash(form.password.data)
        try:
            model = self.model()
            form.populate_obj(model)
            self._on_model_change(form, model, True)
            model.save()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash('Failed to create record')
            return False
        else:
            self.after_model_change(form, model, True)
        return model
    def on_model_change(self, form, model, is_created=False):
        model.password = flask_bcrypt.generate_password_hash(form.password.data)

class MovieView(MyModelView):
    column_filters = ['code']

admin = Admin(app, name='AVDB', template_mode='bootstrap3',base_template='layout.html',
              index_view=MyAdminIndexView(name='Celery Task'))
admin.add_view(UserView(User,name='User'))
admin.add_view(MovieView(Mov,name='Movie'))
admin.add_link(MenuLink(name='Back Home', url='/'))
